<template>
  <div class="box">
    <div>
      <el-card class="box-card box-card-camera" shadow="always">
        <div slot="header" class="clearfix">
          <!-- <el-tag>摄像</el-tag> -->
          <el-button @click="buildImg">start</el-button>
          <el-button @click="destroyImg">stop</el-button>
        </div>
        <img
          id="left_stream1"
          style="height: 400px; width: 400px; object-fit: contain"
          v-bind:src="img"
        />
      </el-card>
    </div>
    <el-card class="box-card card-stick" shadow="always">
      <div slot="header" class="clearfix">
        <el-tag>手柄</el-tag>
      </div>
      <div class="container-stick">
        <div id="stick" ref="stickpan"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ros } from "../js/connect";
import { store } from "../state/store";
import {
  createNewCameTopic,
  subscribeTopic,
  closeCamera,
  openCamera,
  destroyTopic,
} from "../js/camera";
import { createJoyStickWithoutDistance, destroyjoystick } from "../js/joystick";
import {
  createKeyboardListener,
  destroyKeyboardListener,
  //   setKBMaxLinear,
  //   setKBMaxAngular,
} from "../js/keyboard";

export default {
  data() {
    return {
      // img
      imgMsg: "data:image/jpg;base64,",
      imgData: "",
      img: "",
      // control
      topic: null,
      imgStatus: false,
    };
  },
  mounted() {
    createKeyboardListener(document);
    createJoyStickWithoutDistance();
    openCamera(ros);
    // 恢复缓存的图片
    this.imgStatus = store.getCameraStatus();
    if (this.imgStatus) {
      this.img = store.getImg();
      this.buildImg();
    }
  },
  methods: {
    buildImg() {
      var that = this;
      this.topic = createNewCameTopic(ros);
      subscribeTopic(this.topic, function (message) {
        that.imgData = message.data;
        that.img = that.imgMsg + that.imgData;
      });

      this.imgStatus = true;
      store.setCameraStatus(true);
    },
    destroyImg() {
      destroyTopic(this.topic);
      this.img = "";
      this.imgStatus = false;
      store.setCameraStatus(false);
      store.setImg(this.img);
    },
  },
  destroyed() {
    destroyjoystick();
    closeCamera(ros);
    // 组件销毁时根据状态确定是否销毁图像
    if (this.imgStatus) {
      store.setImg(this.img);
    } else {
      store.setImg("");
    }
    // 键盘事件销毁
    destroyKeyboardListener(document);
  },
};
</script>

<style>
.box-card-camera {
  width: 450px;
}
</style>